<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\facade\Session;
use think\Db;

class Bankcard extends Api
{
    //数据添加
    public function add()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            $post = array_filter($post);
            if ($post){
                if(!isset($post['phone']) || !isset($post['user_id']) || !isset($post['number']) || !isset($post['code']) || !isset($post['time']))
                {
                    return fh(404,'error','参数不完整',[]);
                }
            Db::startTrans();
                try{
                    if(!session($post['time'])){
                        return fh(404,'error','验证码失效',[]);
                    }elseif(session($post['time']) !== $post['code']){
                        return fh(404,'error','验证码错误',$post['code']);
                    }
                    $model = model($this->request->controller())->save($post);
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollback();
                    return fh(500,'error',$e->getMessage(),[]);
                }
                return fh(200,'success','添加成功',$model);
            }else{
                return fh(404,'error','没有post数据',[]);
            }
        }
    }
    //虚拟验证码
    public function yzm()
    {
        if($this->request->isPost())
        {
            $post = input('post.');
            $post = array_filter($post);
            if(!isset($post['user_id'])){
                return fh(404,'error','缺少用户ID',[]);
            }
            $codeku = [1,2,3,4,5,6,7,8,9,0];
            $code['code'] = implode('',array_rand($codeku,4));
            $code['time'] = date('YmdHis') . rand(10000,99999);
            Session::flash($code['time'],$code['code']);
            return fh(200,'success','请求成功',$code);
        }
    }
}
